package org.lc.oauth.dto;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import org.lc.platform.base.constant.AuthConstant;
import org.lc.platform.base.enums.AuthResultEnum;
import org.lc.platform.base.enums.LoginResultEnum;

import java.util.List;

@Getter
public class ErrorResult {

    private int code = 40001;
    private String msg = "";


    private void processMixin(String mixin) {
        if (StrUtil.isNotEmpty(mixin)) {
            if (mixin.contains(AuthConstant.EXCEPTION_SPLIT)) {
                List<String> array = List.of(mixin.split(AuthConstant.EXCEPTION_SPLIT));
                this.msg = array.get(0);
                if (NumberUtil.isNumber(array.get(1))) {
                    this.code = Convert.toInt(array.get(1));
                }
            } else {
                this.msg = mixin;
                this.chooseErrorByMsg();
            }
        }
    }

    private void chooseErrorByMsg() {
        switch (this.msg) {
            case AuthConstant.PASSWORD_ERROR:
                this.code = LoginResultEnum.PASS_ERROR.getCode();
                break;
            case AuthConstant.UNSUPPORTED_GRANT_TYPE:
                this.msg = AuthResultEnum.ERROR_GRANT.getMsg();
                this.code = AuthResultEnum.ERROR_GRANT.getCode();
                break;

            case AuthConstant.UNSUPPORTED_CLIENT:
                this.msg = AuthResultEnum.CLIENT_ERROR.getMsg();
                this.code = AuthResultEnum.CLIENT_ERROR.getCode();
                break;
            case AuthConstant.NO_UNSUPPORTED:
                this.msg = AuthResultEnum.FULL_AUTH.getMsg();
                this.code = AuthResultEnum.FULL_AUTH.getCode();
                break;
            case AuthConstant.NO_GRANTTYPE:
                this.msg = AuthResultEnum.NO_GRANT_TYPE.getMsg();
                this.code = AuthResultEnum.NO_GRANT_TYPE.getCode();
                break;
            case AuthConstant.INVALID_GRANT:
                this.msg = AuthResultEnum.INVALID_REFRESH_TOKEN.getMsg() ;
                this.code = AuthResultEnum.INVALID_REFRESH_TOKEN.getCode();
                break;
        }
    }

    public ErrorResult(String mixin) {
        this.processMixin(mixin);
    }

    ErrorResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

}
